package com.cykj.page05;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page05
 * @Author: 阿隆
 * @CreateTime: 2025-10-18 16:19
 * @Description: 多线程服务端
 * @Version: 1.0
 */
public class ThreeServeToThread {
    public static void main(String[] args) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                3,  // 最大线程 >= 核心线程
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        try {
            //创建ServerSocket => 服务器
            ServerSocket serverSocket = new ServerSocket(9091);

            System.out.println("服务端启动端口号为: 9091");

            while (true) {
                //等待客户端连接  阻塞
                Socket socket = serverSocket.accept();

                //创建一条线程
                threadPoolExecutor.execute(new MyTask(socket));
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
